<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2020-09-21 09:39:58
 * @Description: 后台管理权限验证
 * @LastEditors: 李志刚
 * @LastEditTime: 2023-01-16 17:31:32
 * @FilePath: \www.gamemc.com\app\Http\Middleware\ConsoleJwt.php
 */

namespace App\Http\Middleware;

use App\Customize\Func;
use App\Customize\Sign;
use Closure;

class ConsoleJwt {
	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next) {
		try {
			// 先验证签名
			$res = Sign::aes_decrypt($request->all());
			if ($res['code'] != 200) {
				return response()->json(['code' => 403, 'message' => $res['message'] . '...', 'result' => []]);
			}
			// 合并解析到的参数进请求中
			$request->merge($res['result']);
			// 验证 token，解析用户信息，判断权限
            $user = Func::verfiyToken($request->header('Authorization'),'c-token');
			// 拼接权限名字，url的第二个跟第三个参数
			$toArr = explode('/', $request->path());
			if ($toArr[0] != 'c-api') {
				return response()->json(['code' => 402, 'message' => '无权调用此接口数据...', 'result' => '1']);
			}
			// 如果不写方法名，默认为index
			$toArr[2] = count($toArr) == 2 ? 'index' : $toArr[2];
			$permissions = $toArr[1] . '-' . $toArr[2];
			// 在这里进行一部分权限判断，主要是判断打开的页面是否有权限，所有角色ID，所有角色权限累加
			if ($user->id == '1' || in_array(1, $user->allRole) || in_array($permissions, (array) $user->allPermission)) {
				// 日志记录，只记录post或者del操作(通过比较url来得出结果)
                $request->merge(['request_user'=>json_encode($user),'request_permissions'=>$permissions]);
				$response = $next($request);
                // 获取新token
                $response->header('authorization', Func::getToken($user->name,1));
				return $response;
			} else {
				return response()->json(['code' => 402, 'message' => '无权调用此接口数据...', 'result' => '2']);
			}
		} catch (\Throwable $e) {
			return response()->json(['code' => 401, 'message' => '验证权限失败...', 'result' => $e->getMessage()]);
		}
	}
}
